from flask import Flask
from flask_socketio import SocketIO, emit
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.CRITICAL)
socketio = SocketIO(logger=False, engineio_logger=False)
namespace = "/ws"


def init_websocket(app: Flask):
    socketio.init_app(app, cors_allowed_origins='*', always_connect=True)


def publish_msg(message_data):
    socketio.emit(event='message', data=message_data, namespace=namespace)


# 出现消息后,率先执行此处
@socketio.on("message", namespace=namespace)
def socket(message):
    # print(f"接收到消息: {message['data']}")
    for i in range(1, 10):
        socketio.sleep(1)
        socketio.emit("response",  # 绑定通信
                      {"data": i},  # 返回socket数据
                      namespace=namespace)


@socketio.on('connect', namespace=namespace)
def connected_msg():
    print('client connected.')


@socketio.on('disconnect', namespace=namespace)
def disconnect_msg():
    print('client disconnected.')


# 接收客户端消息
@socketio.on('my_event', namespace=namespace)
def mtest_message(message):
    print(message)
    emit('my_response', {'data': message['data'], 'count': 1})
